/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.workflow;

public class AHP{
	private int criteria_S;
	private double[][] priorities;
	private double[] rowSum;
	private double[] weights;
	private static double randomConsistencyIndex[]={0,0,0.52,0.89,1.12,1.26,1.36,1.41,1.46,1.49,1.52,1.54,1.56,1.58,1.59};

	
	public void init(int criteria_S, double[][] priorities) {
		if(criteria_S<=0){
			throw new RuntimeException("cannot init a AHP matric of \"0\" size.");
		}
		setCriteria_S(criteria_S);
		setPriorities(priorities);		
	}
	
	public void calCriteriaWeight() {
		//1.calculate the sum the each column;
		rowSum = new double[criteria_S];
		for(int column=0; column<criteria_S; ++column){
			rowSum[column] = 0;
			for(int row = 0; row<criteria_S; ++row){
				rowSum[column] += priorities[row][column];
			}
		}
		//2.calculate the weight of each criteria.
		weights = new double[criteria_S];
		for(int i=0; i<criteria_S; ++i){
			weights[i] = 0;
			for(int column=0; column<criteria_S; ++column){
				weights[i] += priorities[i][column]/rowSum[column];
			}
			weights[i] = weights[i]/criteria_S;
		}
	}
	
	public boolean consistencyVerify(){
		if(criteria_S <= 2){
			return true;
		}else{
			double maxEigenValue = 0;
			for(int i=0; i<criteria_S; ++i){
				maxEigenValue += rowSum[i]*weights[i];
			}
			double consistencyIndex =(maxEigenValue-criteria_S)/(criteria_S-1);
			double consistencyRatio = consistencyIndex/randomConsistencyIndex[criteria_S-1];
			if(consistencyRatio<0.1){
				return true;
			}else{
				return false;
			}
		}
	}
	
	public int getCriteria_S() {
		return criteria_S;
	}
	public void setCriteria_S(int criteria_S) {
		this.criteria_S = criteria_S;
	}
	
	public double[][] getPriorities() {
		return priorities;
	}
	public void setPriorities(double[][] priorities) {
		this.priorities = priorities;
	}
	public double[] getWeights() {
		return weights;
	}
	public void setWeights(double[] weights) {
		this.weights = weights;
	}
	public double[] getRowSum() {
		return rowSum;
	}
	public void setRowSum(double[] rowSum) {
		this.rowSum = rowSum;
	}
	public double[] getRandomConsistencyIndex() {
		return randomConsistencyIndex;
	}
	
}
